from flask_restplus import Resource, Namespace, fields, marshal, reqparse
from common.decorators import catch_error
from app.storage.storage_flow import service
from app.user.decorators import token_required
from common.responses import ok
from flask import g
from common import constant
from common.response_model import base_model, pagination_model
from common.request_parser import get_parser as base_get_parser

api = Namespace('storage_flow')

# ---------- model ----------
storage_flow_model = base_model.inherit('storage_flow_model', {
    "sku_id": fields.Integer(description='sku id'),
    "warehouse_id": fields.Integer(description='warehouse id'),
    "num": fields.Float(description='数量'),
    'cost_price': fields.Float(description='库存成本单价'),
})
storage_flow_paginate_model = pagination_model.inherit('storage_flow_paginate_model', {
    "items": fields.Nested(storage_flow_model)
})

# ---------- create parser ----------
# ---------- get parser ----------
# 单仓库， 合并仓， 分仓库显示
get_parser = base_get_parser.copy()
get_parser.replace_argument('search_str', type=str, required=True,
                            help='搜索，支持正则 sku_name, sku_sn, sku_short_name')
get_parser.add_argument('warehouse_id', help='warehouse_id', type=int)


# ---------- put parser ----------


class StorageFlowsResource(Resource):
    @catch_error
    @token_required
    @api.expect(get_parser)
    def get(self):
        """获取列表"""
        args = get_parser.parse_args()
        pagination = service.get_by_page(g.user_id, **args)
        return ok(data=marshal(pagination, storage_flow_paginate_model),
                  message='get success')


class StorageFlowResource(Resource):
    @catch_error
    @token_required
    def get(self, obj_id):
        """获取"""
        obj = service.get(g.user_id, obj_id)
        return ok(data=marshal(obj, storage_flow_model),
                  message='get success')


# --------- route ----------
api.add_resource(StorageFlowsResource, '/storage_flows')
api.add_resource(StorageFlowResource, '/storage_flow/<int:obj_id>')

# 注册 response 文档
api.models[storage_flow_model.name] = storage_flow_model
